package com.leetcode.根据数据结构分类.数组;

/**
 * @author: xiaomi
 * @date: 2021/1/28
 * @description: 724. 寻找数组的中心索引
 * https://leetcode-cn.com/problems/find-pivot-index/
 */
public class A_724_寻找数组的中心索引 {

    public static void main(String[] args) {
        int[] nums = new int[]{-1, -1, 0, 1, 0, -1};
        nums = new int[]{-1, -1, 0, 1, 1, 0};
//        nums = new int[]{1, 2, 3};
        A_724_寻找数组的中心索引 action = new A_724_寻找数组的中心索引();
        int res = action.pivotIndex(nums);
        System.out.println("res = " + res);
    }


    /**
     * 这个自认为每个数都是正数，但是不是的。
     * 那么就需要把每个数遍历一遍。
     *
     * @param nums
     * @return
     */
    public int pivotIndex4PositiveNumber(int[] nums) {
        if (nums == null) {
            return -1;
        }
        int len = nums.length;
        if (len == 0) {
            return -1;
        }
        int leftSum = 0;
        int rightSum = 0;
        int index = 0;
        int label = 0;
        //初始化 变量
        for (int i = 1; i < len; i++) {
            rightSum += nums[i];
        }
        label = leftSum == rightSum ? 0 : (leftSum > rightSum ? 1 : -1);

        int endIndex = len - 1;
        //移动指针，进行判断
        while (index < endIndex) {
            if (label == 0) {
                return index;
            }
            leftSum += nums[index];
            rightSum -= nums[++index];
            if (label == 1) {
                //left > right
                if (leftSum < rightSum) {
                    return -1;
                }
            } else {
                if (leftSum > rightSum) {
                    return -1;
                }
            }
            if (leftSum == rightSum) {
                label = 0;
            }
        }
        //此时已经遍历完毕
        return -1;
    }

    private int pivotIndex(int[] nums) {
        if (nums == null) {
            return -1;
        }
        int len = nums.length;
        if (len == 0) {
            return -1;
        }
        int leftSum = 0;
        int rightSum = 0;
        int index = 0;
        for (int i = 1; i < len; i++) {
            rightSum += nums[i];
        }
        int compare = 0;
        while (index < len) {
            compare = leftSum == rightSum ? 0 : (leftSum > rightSum ? 1 : -1);
            if (compare == 0) {
                return index;
            }

            leftSum += nums[index++];
            if (index == len) {
                return -1;
            }
            rightSum -= nums[index];
        }
        return -1;
    }
}
